<?php

namespace App\Http\Controllers\Api\v1;

use App\Business;
use App\Http\Controllers\Controller;
use App\Role;
use App\User;
use Illuminate\Http\Request;

class RoleController extends Controller {

	protected $model, $business, $user;

	public function __construct(Role $role, Business $business, User $user) {
		$this->user = $user;
		$this->model = $role;
		$this->business = $business;
	}

	public function index(Request $request) {
		$users = (new User())->all()->load('business');
		return response(compact('users'));
	}

	public function business($id) {
		$role = (new User)->with('business')->where('six_id', $id)->first();
		if ($role) {
			$role = $role->toArray();
		} else {
			$role = [
				'is_admin' => 0,
				'business' => [],
			];
		}
		$role['is_admin'] == 1 ? array_push($role['business'], ['id' => -1]) : '';
		if (!empty($role['business'])) {
			$role['business'] = array_column($role['business'], 'id');
		}
		$business = $this->business->all()->toArray();
		array_unshift($business, ['id' => -1, 'name' => '管理员']);
		return response(compact('role', 'business'));
	}

	public function store(Request $request) {
		$id = $request->id ?: abort(404);
		$roles = (array) $request->list ?: [];
		$is_admin = 0;
		foreach ($roles as $key => $value) {
			if ($value == -1) {
				$is_admin = 1;
				unset($roles[$key]);
			}
		}
		$roles = array_merge($roles);
		$user = $this->user->where('six_id', $id)->first();
		if (!$user && (!empty($roles) || $is_admin == 1)) {
			$user = $this->user->create(['six_id' => $id, 'is_admin' => $is_admin]);
		} else {
			if ($user->is_admin != $is_admin) {
				$user->is_admin = $is_admin;
				$user->save();
			}
		}
		// if ($roles) {
		$user->business()->sync($roles);
		// }
		echo json_encode(['code' => 0, 'msg' => 'success']);
	}
}
